package com.bjesc_b2c.app.appraiset.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.CarSourcePhotoAdapter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.CarSourcePhotoPersnter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.CarSourcePhotoPersenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CarSourcePhotoView;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.BigCarSourcePhotoActivity;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.CarSourceActivity;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.ProMosaicActivity;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.UploadDialog;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.example.codeutils.utils.FileUtils;
import com.example.codeutils.utils.SDCardUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.CustomLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import master_bean.CarSourcePhotoBean;
import rxretrofit_base.model.KeyBean;

import static com.bjesc_b2c.app.appraiset.utils.TimeListUilts.getObjectKey;

/**
 * Created by lenovo on 2017/2/24.
 * 网格显示图片Activity
 */
public abstract class BaseCarSourcePhotoFragment extends BaseFragment implements CarSourcePhotoView, UploadDialog.FailureUpload {
    protected static final int REQUEST_CODE_CHOOSE = 23;
    @Bind(R.id.recycler_car_source_photo)
    RecyclerView carSourcePhotoRecycler;
    protected CarSourcePhotoAdapter photoAdapter;
    protected List<CarSourcePhotoBean> photoBeanList = new ArrayList<>();
    protected List<CarSourcePhotoBean> copyphotoBeanList = new ArrayList<>();
    protected List<CarSourcePhotoBean> photoFailureList = new ArrayList<>();
    protected List<CarSourcePhotoBean> copyFailureList = new ArrayList<>();
    protected SelectPhotoPop photoPop;
    protected int currentIndex;
    protected Intent bigPhotoIntent;
    protected CarSourceActivity carAty;
    protected CarSourcePhotoPersnter persnter;
    protected List<String> fileList;
    protected String carId;
    private UploadDialog dialog;
    private int failureNum;
    private int uploadSize;
    protected int number = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_car_source, null);
        return contentView;
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
//        if (!hidden) {
//            if (!TextUtils.isEmpty(getSourceID())) {
//                persnter.getPhoto(getSourceID());
//            }
//        }
    }
    protected abstract String getSourceID();

    protected abstract void getSourceList();

    @Override
    public void initView() {
        photoAdapter = new CarSourcePhotoAdapter(getActivity(), R.layout.layout_item_car_source_photo, photoBeanList);
        carSourcePhotoRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3, LinearLayoutManager.VERTICAL, false));
        carSourcePhotoRecycler.setAdapter(photoAdapter);
    }

    @Override
    public void initData() {
        persnter = new CarSourcePhotoPersenterImpl(this, getActivity());
        carAty = (CarSourceActivity) getActivity();
        bigPhotoIntent = new Intent(getActivity(), BigCarSourcePhotoActivity.class);//跳转到大图
        carId = CustomSharedPreferences.getString(mContext, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf());
        getSourceList();
        if (!TextUtils.isEmpty(getSourceID())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String json = FileUtils.readFile2String(SDCardUtils.getDataPath() + carId + File.separator + CarPhotoID.IMAGE_FILE_NAME + getSourceID() + ".txt", "UTF-8");
                    if (!TextUtils.isEmpty(json)) {
                        Logger.d("json=="+json);
                        Gson gson = new Gson();
                        List<CarSourcePhotoBean> userList2 =
                                gson.fromJson(json,
                                        new TypeToken<List<CarSourcePhotoBean>>() {
                                        }.getType());
                        copyphotoBeanList = userList2;
                        Logger.d("photoBeanList====" + photoBeanList.size());
                    }
                }
            }).start();
            photoAdapter.refresh(photoBeanList);
            persnter.getPhoto(getSourceID());
        } else {
            showToast("分类ID为空");
        }
    }

    protected void refreshImage(String url, int index) {
        if (photoBeanList.get(index).getPhotoName().equals("更多")) {        //没有图片名就不添加图片名
            photoBeanList.set(index, new CarSourcePhotoBean(photoBeanList.get(index).getId(), url, ""));
        } else {
            photoBeanList.set(index, new CarSourcePhotoBean(photoBeanList.get(index).getId(), url, photoBeanList.get(index).getPhotoName()));
//            Logger.d("getId" + photoBeanList.get(index).getId());
            Logger.d("url" + photoBeanList.get(index).getPhoto()
            );
            Logger.d("getPhotoName" + photoBeanList.get(index).getPhotoName());
        }
        if (index + 1 == photoBeanList.size()) {   //如果点击的是最后一张，那么就要多添加一张更多
            photoBeanList.add(new CarSourcePhotoBean("-1", "", "更多"));
        }
        photoAdapter.refresh(photoBeanList);
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileUtils.writeFileFromString(SDCardUtils.getDataPath() +
                                carId + File.separator + CarPhotoID.IMAGE_FILE_NAME + getSourceID() + ".txt",
                        new Gson().toJson(photoBeanList), false);
            }
        }).start();
    }
    @Override
    public void getPhoto(List<CarSourcePhotoBean> photoList) {
        if (photoList != null && photoList.size() > 0) {
            this.photoBeanList = photoList;
            if(copyphotoBeanList.size()>0){
                for (int i = 0;i<photoBeanList.size();i++){
                  if (!photoBeanList.get(i).getPhoto().contains("http")){
                         for (int j = 0;j<copyphotoBeanList.size();j++){
                             if (photoBeanList.get(i).getId().equals(copyphotoBeanList.get(j).getId()) ){
                                 photoBeanList.get(i).setPhoto(copyphotoBeanList.get(j).getPhoto());
                         }
                      }
                  }
                }
            }
            photoAdapter.refresh(photoBeanList);
        }
    }
    @Override
    public void getFileName(List<String> fileList) {
        if (fileList != null && fileList.size() > 0) {
            this.fileList = fileList;
        }
    }

    /**
     * 将图片上传到阿里云
     */
    protected void upImgToALiYun() {
        showProgressDialog();
        uploadSize = photoBeanList.size();
        photoFailureList.clear();
        failureNum =0;
        number = 0;
//        Logger.d("uploadSize=="+uploadSize);
        for (int i = 0; i < photoBeanList.size(); i++) {    //循环上传图片到阿里
            if (!photoBeanList.get(i).getId().equals("-1") && !TextUtils.isEmpty(photoBeanList.get(i).getPhoto())) {
                if (!photoBeanList.get(i).getPhoto().contains("http")) {
                    String fileName = getObjectKey() + ".jpg";
                    photoBeanList.get(i).setFileName(fileName);
                    String photoPath = photoBeanList.get(i).getPhoto();//.substring(1);
                    if (photoPath.startsWith("file:/")) {
                        photoPath = photoBeanList.get(i).getPhoto().substring(6);
                    }
                    AliYunUtils.aLiYunUpLoadFuncation(
                            mContext,
                            photoBeanList.get(i).getId(),       //图片ID
                            fileName,                           //图片名
                            photoPath     //图片路径
                            , aliyunListener);
                    Logger.d("getPhoto" + photoBeanList.get(i).getPhoto());
//                    Logger.d("getPhoto id" + photoBeanList.get(i).getId());
//                    Logger.d("fileName " + fileName);
                }else {
                    uploadSize --;
                    if (uploadSize == 0) {
                        dismissProgressDialog();
                    }
                }
            }else{
                uploadSize --;
                if (uploadSize == 0) {
                    dismissProgressDialog();
                }
            }
        }
    }

    private AliYunUtils.OnALiYunUpLoadListener aliyunListener = new AliYunUtils.OnALiYunUpLoadListener() {
        @Override
        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//            CustomLog.d("上传进度 =" + ((currentSize * 100) / totalSize) + "%");
            onALiYunUpImgProgress(request, currentSize, totalSize);
        }

        @Override
        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//            CustomLog.d("上传成功 = " + request.getObjectKey());
            number++;
            CustomLog.d("上传 uploadSize" + uploadSize);
            int pro = number * 100 / uploadSize;
            Message message = new Message();
            message.what = 1;
            message.obj = pro;
            if (dialog != null) {
                dialog.handler.sendMessage(message);
            }
            String[] keyList = request.getObjectKey().split("/");
            Logger.d(keyList.toString());
//            CustomLog.d("上传 成功" + pro);
//            CustomLog.d("上传 number" + number);
//            CustomLog.d("上传 failureNum" + failureNum);
//            CustomLog.d("上传 uploadSize" + uploadSize);
            if (uploadSize == number+failureNum && dialog != null) {
                if(failureNum == 0){
                   dialog.handler.sendEmptyMessage(4);
               }else {
                    Message message2 = new Message();
                    message2.what = 2;
                    message2.obj = failureNum;
                    dialog.handler.sendMessage(message2);
                }
                number = 0;
                failureNum = 0;
            }
            onALiYunUpImgSuccess(request, result);
        }

        @Override
        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
            CustomLog.d("上传失败 = " + request.getObjectKey());
            failureNum++;
            String[] keyList = request.getObjectKey().split("/");
            String photo = "";
            String pName = "";
//            number++;
            if (uploadSize == number+failureNum) {
                Message message = new Message();
                message.what = 2;
                message.obj = failureNum;
                if (dialog != null) {
                    dialog.handler.sendMessage(message);
                }
                number = 0;
                failureNum = 0;
            }
            for (int i = 0; i < photoBeanList.size(); i++) {
                if (photoBeanList.get(i).getFileName().equals(keyList[2])) {
                    photo = photoBeanList.get(i).getPhoto();
//                    CustomLog.d("上传失败  photo =" + photo);
//                    Logger.d("上传失败keyList[1]=="+keyList[1]);
//                    Logger.d("上传失败keyList[0]=="+keyList[0]);
//                    Logger.d("上传失败keyList[2]=="+keyList[2]);
                    photoFailureList.add(new CarSourcePhotoBean(keyList[1], photo, keyList[2]));
                    break;
                }
            }
            CustomLog.d("上传失败 = " + photoFailureList.size());
            if (serviceException != null) {
                // 服务异常
                CustomLog.d("___aliyun_ErrorCode = " + serviceException.getErrorCode());
                CustomLog.d("___aliyun_RequestId = " + serviceException.getRequestId());
                CustomLog.d("___aliyun_HostId = " + serviceException.getHostId());
                CustomLog.d("___aliyun_RawMessage = " + serviceException.getRawMessage());
            }
            if (clientExcepion != null) {
                // 本地异常如网络异常等
                CustomLog.d(clientExcepion.getMessage());
//                FileNotFoundException
            }
        }
    };

    @Override
    public void upload() {
//        failureNum =0;
//        number = 0;
        if (photoFailureList.size() == 0){
            dismissProgressDialog();
            return;
        }
        uploadSize = photoFailureList.size();
        copyFailureList.clear();
        copyFailureList.addAll(photoFailureList);
        photoFailureList.clear();
        Logger.d("uploadSize=="+uploadSize);
       for (int i =0;i<copyFailureList.size();i++) {
           String photoPath = copyFailureList.get(i).getPhoto();//.substring(1);
           if (photoPath.startsWith("file:/")) {
               photoPath = copyFailureList.get(i).getPhoto().substring(6);
           }
           AliYunUtils.aLiYunUpLoadFuncation(
                   getActivity(),
                   copyFailureList.get(i).getId(),       //图片ID
                   copyFailureList.get(i).getPhotoName(),//图片名 这里的 PhotoName()的值和  fileName一样
                   photoPath     //图片路径
                   , aliyunListener);
//           CustomLog.d("重新上传 = " +  copyFailureList.get(i).getId());
//           CustomLog.d("重新上传 = " +  copyFailureList.get(i).getPhotoName());
//           CustomLog.d("重新上传 = " +  copyFailureList.get(i).getPhoto());
       }
//        photoFailureList.clear();
        Message message = new Message();
        message.what = 3;
        if (dialog != null) {
            dialog.handler.sendMessage(message);
        }
    }
    private void showProgressDialog() {
        if (dialog == null) {
            dialog = new UploadDialog(getActivity(), this);
            dialog.setCanceledOnTouchOutside(false);
        }
        dialog.show();
    }

    private void dismissProgressDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }


    //阿里的上传进度回调，没需要可以不重写
    protected void onALiYunUpImgProgress(PutObjectRequest request, long currentSize, long totalSize) {

    }

    //阿里的上传成功回调，没需要可以不重写
    protected void onALiYunUpImgSuccess(PutObjectRequest request, PutObjectResult result) {

    }

    //阿里的上传成功回调，没需要可以不重写
    protected void onALiYunUpImgFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {

        if (serviceException.getErrorCode().equals("RequestTimeout")) {
            showToast("请求超时");
        }
        if (clientExcepion != null) {
            // 本地异常如络异常等
            showToast("图片上传失败 网络状态不好");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
         if(rxBusBean.getRequestMark().equals(ProMosaicActivity.class.getName())){
             initData();
        }
    }
}
